import express from 'express'
import { body, query } from 'express-validator'
import {mysqlDataSource} from '../config/mysqlDataSource.js'
import { User } from "../entity/User.js";
import { Result} from '../config/Result.js'
import {compare} from '../utils/bcrypt.js'
import {createToken} from '../utils/jwt.js'
import {
	setRedisTokenData,
	getRedisCaptchaData,
	removeRedisCaptchaData
} from '../utils/redisClient.js'
import {handleExpressValidate} from '../utils/handleExpressValidate.js'

const router = express.Router()

/**
 * @apiDefine auth
 * AUTH模块
 */

/**
 * @api {post} /auth/login 登录
 * @apiDescription 用户名密码验证码登录
 * @apiVersion 1.0.0
 * @apiName authLogin
 * @apiGroup auth
 * @apiBody {String} username=ares 用户名
 * @apiBody {String} password=123456 用户密码
 * @apiBody {String} code 验证码
 * @apiSampleRequest /auth/login
 * @apiUse auth
 */
router.post('/login',[
	body('username').notEmpty().withMessage('用户名不能为空'),
	body('password').notEmpty().withMessage('密码不能为空'),
	body('code').notEmpty().withMessage('密码不能为空')
], async (req, res) => {
	if(!handleExpressValidate(req, res)) return;

	const {username, password, code} = req.body

	const sessionId = req.sessionID
	const redisCode = await getRedisCaptchaData(sessionId)
	if (!redisCode) {
		return res.send(Result.fail('验证码无效'))
	}
	if (redisCode !== code) {
		return res.send(Result.fail('验证码错误'))
	}
	await removeRedisCaptchaData(sessionId)

	mysqlDataSource.manager.findOneBy(User,  {username}).then(user => {
		if (!user) {
			return res.send(Result.fail('用户不存在'))
		}else {
			if (compare(password, user.password)) {
				const token = createToken({username, userId: user.id})
				setRedisTokenData(user.id, token)
				return res.send(Result.success(token))
			}else {
				return res.send(Result.fail('密码错误'))
			}
		}
		res.send(Result.coreFail(null))
	})

})

/**
 * @api {get} /auth/getUserById 根据用户ID查询用户信息
 * @apiDescription 根据用户ID查询用户信息
 * @apiVersion 1.0.0
 * @apiName authGetUserById
 * @apiGroup auth
 * @apiHeader {String} Authorization token
 * @apiQuery {String} userId 用户ID
 * @apiSampleRequest /auth/getUserById
 * @apiUse auth
 */
router.get('/getUserById',[query('userId').isInt().withMessage('用户ID只能为整数')], (req, res) => {
	if(!handleExpressValidate(req, res)) return;

	mysqlDataSource.manager.findOneBy(User,  {id: req.query.userId}).then(user => {
		res.send(Result.success(user))
	})
})



export default router
